<template>
  <div class="duration-manager-container">
    <!-- 页面标题与操作区 -->
    <div class="page-header action-buttons">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索课程时长名称..."
        prefix-icon="fas fa-search"
        clearable
        @input="handleSearch"
      ></el-input>
      <el-button @click="loadData">
        <i class="fas fa-search" aria-hidden="true"/>
        查询
      </el-button>
      <el-button type="primary" @click="showAddDialog = true">
        <i class="fas fa-plus" aria-hidden="true"/>
        新增时长
      </el-button>
    </div>

    <!-- 课程时长卡片列表 -->
    <div class="duration-card-list">
      <!-- 筛选后的卡片 -->
      <div
        class="duration-card"
        v-for="(duration, index) in filteredDurations"
        :key="duration.id"
      >
        <div class="card-content">
          <div class="card-title">
            <span class="name">{{ duration.name }}</span>
            <span class="time-badge">{{ duration.minutes }} 分钟</span>
          </div>
          <div class="card-desc">
            <span class="time-badge">每节课消耗 {{ duration.classHour }} 课时</span>
          </div>
          <div class="card-desc">
            <span>创建时间：{{ formatDate(duration.createTime) }}</span>
          </div>
        </div>
        <div class="card-actions">
          <el-button
            size="mini"
            icon="fas fa-edit"
            @click="handleEdit(duration)"
          />
          <el-button
            size="mini"
            icon="fas fa-trash"
            class="delete-btn"
            @click="handleDelete(duration.id)"
          />
        </div>
      </div>

      <!-- 空状态（无数据或无搜索结果） -->
      <div v-if="filteredDurations.length === 0" class="empty-state">
        <i class="fas fa-clock" aria-hidden="true"/>
        <p>{{ searchKeyword ? '未找到匹配的课程时长' : '暂无课程时长数据' }}</p>
      </div>
    </div>

    <!-- 新增/编辑课程时长对话框 -->
    <el-dialog
      :title="editingDuration ? '编辑课程时长' : '新增课程时长'"
      :visible.sync="showAddDialog"
      :close-on-click-modal="false"
      center
      :show-close="false"
    >
      <el-form
        ref="durationForm"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="时长名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入课程时长名称（如：单词60分钟体验课、单词30分钟课）"
          />
        </el-form-item>
        <el-form-item label="时长(分钟)" prop="minutes">
          <el-input
            v-model.number="formData.minutes"
            placeholder="请输入时长（整数）"
            type="number"
            min="1"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { courseDurationTypeList, createdOrUpdate } from '@/api/wordSystemCourseDurationType'

export default {
  name: 'CourseDurationManager',
  data() {
    return {
      // 搜索关键词
      searchKeyword: '',
      // 显示新增/编辑对话框
      showAddDialog: false,
      // 正在编辑的时长数据（null表示新增）
      editingDuration: null,
      // 表单数据
      formData: {
        name: '',
        minutes: ''
      },
      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '请输入时长名称', trigger: 'blur' },
          { max: 20, message: '名称长度不能超过20个字符', trigger: 'blur' }
        ],
        minutes: [
          { required: true, message: '请输入时长', trigger: 'blur' },
          { type: 'number', message: '请输入有效的数字', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value < 1) {
                callback(new Error('时长不能小于1分钟'))
              } else {
                callback()
              }
            }, trigger: 'blur'
          }
        ]
      },
      // 课程时长数据源（实际项目中可替换为接口数据）
      durationList: []
    }
  },
  computed: {
    // 筛选后的课程时长列表
    filteredDurations() {
      if (!this.searchKeyword) return this.durationList
      // 模糊匹配时长名称
      return this.durationList.filter(item =>
        item.name.toLowerCase().includes(this.searchKeyword.toLowerCase())
      )
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    async loadData() {
      const res = await courseDurationTypeList({
        param: {
          keyword: this.searchKeyword
        }
      })

      res.forEach(item => {
        item.createTime = this.formatDate(item.createTime)
        item.minutes = item.duration
      })
      this.durationList = res
    },
    // 处理搜索
    handleSearch() {
      // 依赖computed自动更新筛选结果，无需额外逻辑
    },

    // 处理编辑
    handleEdit(duration) {
      // 深拷贝选中的时长数据到表单
      this.editingDuration = { ...duration }
      this.formData = {
        name: duration.name,
        minutes: duration.minutes
      }
      this.showAddDialog = true
    },

    // 处理删除
    handleDelete(id) {
      this.$confirm('确定要删除该课程时长吗？删除后不可恢复', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 过滤掉被删除的项
        this.durationList = this.durationList.filter(item => item.id !== id)
        this.$notify.success('课程时长已删除')
      }).catch(() => {
        // 取消删除
      })
    },

    // 关闭对话框并重置表单
    closeDialog() {
      this.showAddDialog = false
      this.resetForm()
    },
    // 提交表单（新增/编辑）
    submitForm() {
      this.$refs.durationForm.validate(async valid => {
        if (valid) {
          if (this.editingDuration) {
            // 编辑模式：更新现有数据
            const editDuration = {
              id: this.editingDuration.id,
              name: this.formData.name,
              duration: this.formData.minutes
            }
            await createdOrUpdate(editDuration)
            await this.loadData()
            this.$notify.success('课程时长已更新')
          } else {
            // 新增模式：添加新数据
            const newDuration = {
              name: this.formData.name,
              duration: this.formData.minutes
            }
            await createdOrUpdate(newDuration)
            await this.loadData()
            this.$notify.success('课程时长已添加')
          }
          this.closeDialog()
        }
      })
    },
    // 重置表单
    resetForm() {
      this.editingDuration = null
      this.formData = {
        name: '',
        minutes: ''
      }
      this.$refs.durationForm.resetFields()
    }
    ,

// 格式化日期显示
    formatDate(date) {
      const d = new Date(date)
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.duration-manager-container {
  padding: 20px;
  margin: 0 auto;
  box-sizing: border-box;
}

/* 页面标题与操作区 */
.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

/* 卡片列表 */
.duration-card-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

/* 时长卡片 */
.duration-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(8, 8, 8, 0.15); /* 阴影 */
  padding: 18px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  transition: box-shadow 0.3s ease;
}

.duration-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.card-content {
  margin-bottom: 15px;
}

.card-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.time-badge {
  display: inline-block;
  padding: 3px 10px;
  background-color: #f0f7ff;
  color: #0084ff;
  border-radius: 15px;
  font-size: 12px;
  font-weight: 500;
}

.card-desc {
  font-size: 12px;
  color: #999;
  margin-top: 10px;
}

/* 卡片操作按钮 */
.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* 空状态 */
.empty-state {
  grid-column: 1 / -1; /* 占满所有列 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  text-align: center;
  background-color: #fff;
  border-radius: 12px;
}

.empty-state i {
  font-size: 56px;
  color: #ddd;
  margin-bottom: 20px;
}

.empty-state p {
  font-size: 16px;
  color: #999;
  margin: 0 0 25px 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-bar .el-input {
    width: 100%;
  }

  .duration-card-list {
    grid-template-columns: 1fr;
  }
}

/* 操作按钮区 */
.action-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.action-buttons .el-button {
  border-radius: 8px;
  padding: 8px 16px;
}

.action-buttons .el-button i {
  margin-right: 6px;
}

.action-buttons .el-input {
  width: 200px;
}

.card-actions .el-button {
  padding: 4px 8px;
  border-radius: 6px;
}

.delete-btn {
  color: #ff4d4f;
  border-color: #ffccd5;
  background-color: #fff2f2;
}
</style>
